package com.cn.jinl.service;

import com.cn.jinl.api.IOrderBackInfoService;
import com.cn.jinl.api.IOrderService;
import com.cn.jinl.dao.OrderBackInfoMapper;
import com.cn.jinl.dao.OrderMapper;
import com.cn.jinl.dao.ProductStorageOutRelateMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.GenerateUUID;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class OrderBackInfoServiceImpl implements IOrderBackInfoService {

    @Autowired
    private OrderBackInfoMapper orderBackInfoMapper;

    @Autowired
    private GenerateUUID generateUUID;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<OrderBackInfo> getOrderBackInfoList(QueryForm queryForm) throws Exception {
        int count = orderBackInfoMapper.selectOrderBackListCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<OrderBackInfo> orders = orderBackInfoMapper.selectOrderBackList(queryForm);
        orders.get(0).setCount(count);
        return orders;
    }

    @Override
    public OrderBackInfo getOrderBackInfoById(String id) throws Exception {
        OrderBackInfo exist = orderBackInfoMapper.selectOrderBackInfoByKey(id);
        return exist;
    }

    @Override
    public OrderBackInfo getOrderBackInfoByOrderId(String orderId) throws Exception {
        return orderBackInfoMapper.selectOrderBackInfoByOrderId(orderId);
    }


    @Override
    public String addOrderBackInfo(OrderBackInfo orderBackInfo) throws Exception {
        OrderBackInfoExample example = new OrderBackInfoExample();
        example.createCriteria().andOrderIdEqualTo(orderBackInfo.getOrderId()).andOrderBackStatusNotEqualTo("5");
        int existCount = orderBackInfoMapper.countByExample(example);
        if(existCount > 0){
            return "订单已经存在退货记录！";
        }
        String id = CommonUtil.generateRandomNum("orderback-");
        orderBackInfo.setId(id);
        String key = "TH"+generateUUID.getYearTwoStr();
        int num = generateUUID.getNumberFlag(key);
        String code = key+generateUUID.getFourNumStr(num);
        orderBackInfo.setOrderBackCode(code);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String handleTime = simpleDateFormat.format(new Date());
        orderBackInfo.setHandleTime(handleTime);
        int count = orderBackInfoMapper.insertSelective(orderBackInfo);
        return CommonUtil.outStr(count);
    }

    @Override
    public String disOrderBackInfo(OrderBackInfo orderBackInfo) throws Exception {
        String id = orderBackInfo.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id不能为空！";
        }
        OrderBackInfo exist = orderBackInfoMapper.selectOrderBackInfoByKey(id);
        if(null == exist){
            return "未查询到退货任务！";
        }
        if(StringUtils.equals(exist.getOrderBackStatus(),"3")|| StringUtils.equals(exist.getOrderBackStatus(),"4")){
            return "退货已经入库，退货任务无法取消";
        }
        OrderBackInfo update = new OrderBackInfo();
        update.setOrderBackStatus("5");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String disTime = simpleDateFormat.format(new Date());
        update.setDisOrderTime(disTime);
        update.setDisOrderUser(orderBackInfo.getDisOrderUser());
        OrderBackInfoExample example = new OrderBackInfoExample();
        example.createCriteria().andIdEqualTo(id);
        int count = orderBackInfoMapper.updateByExampleSelective(update,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrderBackInfo(OrderBackInfo orderBackInfo) throws Exception {
        String id = orderBackInfo.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id不能为空！";
        }
        OrderBackInfoExample example = new OrderBackInfoExample();
        example.createCriteria().andIdEqualTo(id);
        int count = orderBackInfoMapper.updateByExampleSelective(orderBackInfo,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateOrderBackSure(OrderBackInfo orderBackInfo) throws Exception {
        String id = orderBackInfo.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id不能为空！";
        }
        OrderBackInfo exist = orderBackInfoMapper.selectOrderBackInfoByKey(id);
        if(null == exist){
            return "未查询到退货任务！";
        }
        if(!StringUtils.equals(exist.getOrderBackStatus(),"1")){
            return "退货不在待确认状态！";
        }

        orderBackInfo.setOrderBackStatus("2");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sureTime = simpleDateFormat.format(new Date());
        orderBackInfo.setSureTime(sureTime);
        String resp = this.updateOrderBackInfo(orderBackInfo);
        return resp;
    }

    @Override
    public String updateOrderBackComplete(OrderBackInfo orderBackInfo) throws Exception {
        String id = orderBackInfo.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id不能为空！";
        }
        OrderBackInfo exist = orderBackInfoMapper.selectOrderBackInfoByKey(id);
        if(null == exist){
            return "未查询到退货任务！";
        }
        if(!StringUtils.equals(exist.getOrderBackStatus(),"3")){
            return "退货不在待处理状态！";
        }

        orderBackInfo.setOrderBackStatus("4");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sureTime = simpleDateFormat.format(new Date());
        orderBackInfo.setCompleteTime(sureTime);
        String resp = this.updateOrderBackInfo(orderBackInfo);
        return resp;
    }

    @Override
    public List<OrderBackInfo> getFirstPageOrderUnBackStorageList() throws Exception {
        return orderBackInfoMapper.selectOrderUnBackStorageList();
    }

    @Override
    public int getOrderBackInfoing() throws Exception {
        List<String> statusList = Lists.newArrayList("0","1","2","3");
        OrderBackInfoExample example = new OrderBackInfoExample();
        example.createCriteria().andStatusEqualTo(Constants.NORMAL_STATUS).andOrderBackStatusIn(statusList);
        return orderBackInfoMapper.countByExample(example);
    }

    @Override
    public List<OrderBackInfo> getAPIOrderBackInfoList(QueryForm queryForm) throws Exception {
        return orderBackInfoMapper.selectAPIOrderBackList(queryForm);
    }

    @Override
    public List<OrderBackInfo> getOrderBackStorageList(QueryForm queryForm) throws Exception {
        return orderBackInfoMapper.selectAPIOrderBackStorageList(queryForm);
    }

    @Override
    public List<OrderBackStorageVo> getAPIOrderBackHasStorageList(QueryForm queryForm) throws Exception {
        return orderBackInfoMapper.selectAPIOrderBackHasStorageList(queryForm);
    }

    @Override
    public String updateBaoshuOrderBackInfo(OrderBackInfo orderBackInfo) throws Exception {
        String id = orderBackInfo.getId();
        if(StringUtils.isEmpty(id)){
            return "主键id不能为空！";
        }
        OrderBackInfo exist = orderBackInfoMapper.selectOrderBackInfoByKey(id);
        if(null == exist){
            return "未查询到退货任务！";
        }
        if(!StringUtils.equals(exist.getOrderBackStatus(),"0")){
            return "退货不在待报数状态！";
        }
        String wuliuCount = orderBackInfo.getWuliuCount();
        if(StringUtils.isEmpty(wuliuCount)||Integer.parseInt(wuliuCount) <=0){
            return "物流到件数必须大于0";
        }
        orderBackInfo.setOrderBackStatus("1");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String baoshuTime = simpleDateFormat.format(new Date());
        orderBackInfo.setBaoshuTime(baoshuTime);
        String resp = this.updateOrderBackInfo(orderBackInfo);
        return resp;
    }

    @Override
    public List<Map<Object, Object>> getDataAnalysisList() throws Exception {
        QueryForm queryForm = new QueryForm();
        List<Map<Object, Object>> resultList = new ArrayList<>();
        int currentYear = LocalDate.now().getYear();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i <= 3; i++) {
            int year = currentYear - i;
            LocalDateTime startTime = LocalDateTime.of(year, 1, 1, 0, 0, 0);
            LocalDateTime endTime   = LocalDateTime.of(year, 12, 31, 23, 59, 59);
            queryForm.setStartTime(startTime.format(fmt));
            queryForm.setEndTime(endTime.format(fmt));
            int count = orderMapper.getDataAnalysisCount(queryForm);
            //退货
            List<String> statusList = new ArrayList<>();
            statusList.add("4");
            queryForm.setStatusList(statusList);
            int thCount = orderBackInfoMapper.selectOrderBackListCount(queryForm);

            Map<Object, Object> map = new HashMap<>();
            map.put("year",  String.valueOf(year));
            map.put("count", count);
            map.put("thdds", thCount);
            if (count > 0) {
                double ratio = (double) thCount / count * 100;
                map.put("bfb", String.format("%.2f%%", ratio));
            } else {
                map.put("bfb", thCount > 0 ? "100%" : "0%");
            }
            resultList.add(map);
        }
        return resultList;
    }
}
